package com.huashi.demo;

import java.util.*;

public class LevelOrder {
    public int[] levelOrder(TreeNode root){
        ArrayList<Integer> result = new ArrayList<>();
        ArrayList<TreeNode> tree = new ArrayList<>();

        //放入根节点
        if (root == null)
            return new int[0];
        tree.add(root);

        while (!tree.isEmpty()){
            root = tree.get(0);
            tree.remove(0);
            result.add(root.val);
            //依次将每层节点放入
            if (root.left!=null){
                tree.add(root.left);
            }
            if (root.right!=null){
                tree.add(root.right);
            }
        }

        //存储
        int size = result.size();
        int[] R = new int[size];
        for (int i=0;i<size;i++){
            R[i] = result.get(i);
        }
        return R;
    }

    private List<List<Integer>> ret;

    public List<List<Integer>> levelOrderT(TreeNode root) {
        ret = new ArrayList<>();
        dfs(0, root);
        return ret;
    }

    private void dfs(int depth, TreeNode root) {
        if (root == null) {
            return;
        }
        if (ret.size() == depth) {
            ret.add(new ArrayList<>());
        }
        ret.get(depth).add(root.val);
        if (depth%2!=0){
            dfs(depth + 1, root.left);
            dfs(depth + 1, root.right);
        }else {
            dfs(depth+1, root.right);
            dfs(depth+1, root.left);
        }

    }
}
